<template>
  <base-layout>
    <template v-if="selectedResult">
      <result-detail 
        :result="selectedResult" 
        @back="selectedResult = null" 
      />
    </template>

    <template v-else-if="hasSearched && searchResults.length > 0">
      <search-results 
        :search-results="searchResults"
        :visible-results="visibleResults"
        :has-more-results="hasMoreResults"
        :is-expanded="isExpanded"
        :remaining-results="remainingResults"
        :ai-answer="aiAnswer"
        :current-text="currentText"
        :is-typing="isTyping"
        @tag-click="handleTagClick"
        @toggle-results="toggleResults"
      />
    </template>

    <template v-else-if="hasSearched">
      <empty-results />
    </template>

    <template v-else>
      <welcome-guide 
        :suggestion-tags="suggestionTags"
        @suggestion-click="handleSuggestionClick"
      />
    </template>
  </base-layout>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { marked } from 'marked';
import BaseLayout from './BaseLayout.vue';
import SearchResults from './SearchResults.vue';
import ResultDetail from './ResultDetail.vue';
import WelcomeGuide from './WelcomeGuide.vue';
import EmptyResults from './EmptyResults.vue';

const selectedResult = ref(null);
const hasSearched = ref(false);
const isExpanded = ref(false);
const INITIAL_VISIBLE_COUNT = 6;
const currentText = ref('');
const isTyping = ref(false);

// 示例搜索建议
const suggestionTags = [
  '2025年 AI 发展趋势',
  '人工智能最新突破',
  '机器学习应用案例',
  'AI 助手对比评测',
  '自然语言处理技术'
];

const emit = defineEmits(['suggestion-click']);

const formatContent = (content) => {
  if (!content) return '';
  return marked(content);
};

const formatTime = (isoString) => {
  const date = new Date(isoString);
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

const props = defineProps({
  searchResults: {
    type: Array,
    default: () => []
  },
  aiAnswer: {
    type: String,
    default: ''
  },
  streamingEnabled: {
    type: Boolean,
    default: true
  }
});

// 监听 aiAnswer 变化，实现打字机效果
watch(() => props.aiAnswer, async (newValue) => {
  if (!newValue || !props.streamingEnabled) {
    currentText.value = newValue;
    return;
  }

  isTyping.value = true;
  currentText.value = '';
  
  const words = newValue.split('');
  for (let i = 0; i < words.length; i++) {
    currentText.value += words[i];
    // 调整打字速度，当前是每字符 20ms
    await new Promise(resolve => setTimeout(resolve, 20));
  }
  
  isTyping.value = false;
}, { immediate: true });

// 监听 searchResults 变化
watch(() => props.searchResults, (newValue) => {
  // 只有当真正有搜索结果时才设置 hasSearched 为 true
  hasSearched.value = newValue.length > 0 || props.aiAnswer;
}, { immediate: true });

const handleTagClick = (tag) => {
  selectedResult.value = {
    title: tag.name,
    url: tag.url,
    snippet: tag.snippet
  };
};

const handleSuggestionClick = (suggestion) => {
  emit('suggestion-click', suggestion);
};

const visibleResults = computed(() => {
  if (isExpanded.value) {
    return props.searchResults;
  }
  return props.searchResults.slice(0, INITIAL_VISIBLE_COUNT);
});

const remainingResults = computed(() => {
  return props.searchResults.length - INITIAL_VISIBLE_COUNT;
});

const hasMoreResults = computed(() => {
  return props.searchResults.length > INITIAL_VISIBLE_COUNT;
});

const toggleResults = () => {
  isExpanded.value = !isExpanded.value;
};
</script>

<style scoped>
/* 将相关样式移动到各自的组件中 */
</style>